package com.scau.phr.business.auth.service;

import com.google.common.cache.Cache;
import com.google.common.cache.CacheBuilder;
import com.scau.phr.business.auth.domain.Session;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;

import java.util.concurrent.TimeUnit;

/**
 * 内存Session服务
 * @author yuzhiyi
 * @date 2018/7/29 17:32
 */
@Service(SimpleSessionServiceImpl.NAME)
public class SimpleSessionServiceImpl implements SessionService {

	Logger logger = LoggerFactory.getLogger(SimpleSessionServiceImpl.class);

	public static final String NAME = "SimpleSessionService";

	private Cache<String,Session> sessionCache;

	private ThreadLocal<Session> currentThreadSession = new ThreadLocal<>();

	public SimpleSessionServiceImpl(){
		sessionCache = CacheBuilder.newBuilder()
				//有效期一天
				.expireAfterWrite(24, TimeUnit.HOURS)
				//当内存不足的时候自动回收
				.softValues()
				//当session被销毁的时候记录到log中
				.removalListener(rn->{
					logger.debug("token:{} session销毁",rn.getKey());
				})
				//最多有10000个Session
				.maximumSize(10000)
				.build();
	}

	@Override
	public Session getSession(String token) {
		return sessionCache.getIfPresent(token);
	}

	@Override
	public void destroySession(String token) {
		sessionCache.invalidate(token);
	}

	@Override
	public Session addSession(String token, Session session) {
		logger.debug("token:{},username:{} 加入session",token,session.getUsername());
		sessionCache.put(token,session);
		return session;
	}

	@Override
	public Session getCurrentSession() {
		return currentThreadSession.get();
	}

	@Override
	public void setCurrentSession(String token) {
		currentThreadSession.set(getSession(token));
	}

	@Override
	public boolean validSession(String token) {
		return sessionCache.getIfPresent(token) != null;
	}
}
